package com.zlsy.thread.concurrentcontainer;

import java.util.concurrent.ArrayBlockingQueue;

/**
 * @author zhouliang
 * @date 2020/8/31 14:34
 */
public class ArrayBlockingQueueDemo {
    public static void main(String[] args) {
        ArrayBlockingQueue<String> queue = new ArrayBlockingQueue<>(3);

        Interviewer r1 = new Interviewer(queue);
        Consumer r2 = new Consumer(queue);

        new Thread(r1).start();
        new Thread(r2).start();
    }
}

class Interviewer implements Runnable {
    private ArrayBlockingQueue<String> queue;

    public Interviewer(ArrayBlockingQueue<String> queue) {
        this.queue = queue;
    }

    @Override
    public void run() {
        System.out.println("10个候选人都来了");
        try {
            for (int i = 0; i < 10; i++) {
                String candidate = "candidate" + i;
                queue.put(candidate);
                System.out.println("安排好了:" + candidate);
            }
            queue.put("stop");
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
    }
}

class Consumer implements Runnable {

    private ArrayBlockingQueue<String> queue;

    public Consumer(ArrayBlockingQueue<String> queue) {
        this.queue = queue;
    }

    @Override
    public void run() {
        try {
            Thread.sleep(1000);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        String msg = "";
        try {
            while (!(msg = queue.take()).equals("stop")) {
                System.out.println("到了：" + msg);
            }
            System.err.println("所有候选人都结束了。");
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
    }
}